package com.test.com.bluetoothchatandroid.thread;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import com.orhanobut.logger.Logger;
import com.test.com.bluetoothchatandroid.global.ChatConstant;
import com.test.com.bluetoothchatandroid.utils.BluetoothChatHelper;

import java.io.IOException;

/**
 * Created by ${cs} on 2018/4/20.
 *  连接线程
 */

public class ConnectThread extends Thread {

	private final BluetoothChatHelper mHelper;
	private final BluetoothSocket mSocket;
	private final BluetoothDevice mDevice;
	private String mSocketType;

	public ConnectThread(BluetoothChatHelper helper, BluetoothDevice device,boolean secure) {
		this.mHelper = helper;
		this.mDevice = device;
		BluetoothSocket socket = null;
		mSocketType = secure?"SECURE":"INSECURE";

		try{
			if (secure){
				socket = device.createRfcommSocketToServiceRecord(ChatConstant.UUID_SECURE);
			}else {
				socket = device.createInsecureRfcommSocketToServiceRecord(ChatConstant.UUID_INSECURE);
			}
		} catch (IOException e) {
			Logger.d("创建socket "+mSocketType+"创建失败 "+e.getMessage());
		}
		mSocket = socket;
	}
	@Override
	public void run() {
		Logger.d("连接 线程 套接字类型："+mSocketType);
		setName("ConnectThread "+mSocketType);
		// 开启新的线程 关闭发现线程
		mHelper.getAdapter().cancelDiscovery();

		try {
			mSocket.connect();
		} catch (IOException e) {
			try {
				mSocket.close();
			} catch (IOException e1) {
				Logger.d("套接字连接异常下 套接字关闭异常"+e.getMessage());
			}
			mHelper.connectionFailed();
			return;
		}
		synchronized (this){
			Logger.d("连接线程同步锁");
			mHelper.setConnectThread(null);
		}
		mHelper.connected(mSocket,mDevice,mSocketType);
	}


	public void cancel(){
		try {
			mSocket.close();
		} catch (IOException e) {
			Logger.d("线程 "+mSocketType+" 取消 关闭套接字失败"+e.getMessage());
		}
	}
}
